/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.wiki.services;

import foo.bar.wiki.domain.User;
import foo.bar.wiki.domain.Space;
import foo.bar.wiki.utils.CollectionUtils;
import foo.bar.wiki.utils.Transformer;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import java.util.List;
import java.util.ArrayList;

/**
 * Serivce that handles the translation in {@link foo.bar.wiki.security.ExtendedWildcardPermission2}.
 *
 * @author tmjee
 * @version $Date$ $Id$
 */
public class UserExtendedWildcardPermissionService extends AbstractJpaAwareService {

    UserExtendedWildcardPermissionService(){}
    public UserExtendedWildcardPermissionService(JpaTemplate template) {
        super(template);
    }

    public List<String> getMemberSpaceId(final User user) {
        return (List<String>) getJpaTemplate().execute(new JpaCallback(){
            public Object doInJpa(EntityManager em) throws PersistenceException {

                Query q = em.createNamedQuery("Space_findUserMemberSpace");
                q.setParameter("userId", user.getId());
                List<Space> spaces = q.getResultList();
                return CollectionUtils.collect(spaces, new Transformer<Space, String>() {
                    public String transform(Space space) {
                        return space.getId();
                    }
                });
            }
        });
    }

    public List<String> getOwnerSpaceId(final User user) {
        return (List<String>) getJpaTemplate().execute(new JpaCallback(){
            public Object doInJpa(EntityManager em) throws PersistenceException {

                Query q = em.createNamedQuery("Space_findUserOwnerSpace");
                q.setParameter("user", user);
                List<Space> spaces = q.getResultList();
                return CollectionUtils.collect(spaces, new Transformer<Space, String>() {
                    public String transform(Space space) {
                        return space.getId();
                    }
                });
            }
        });
    }
}
